package com.lepu.app.fun.chat.controller.base;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.jivesoftware.smack.util.StringUtils;

import common.db.alummage.ImageItem;
import util.BimpUtils;
import util.CheckNetUtil;
import util.DateUtil;
import util.KeyBoardUtil;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.content.LocalBroadcastManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.app.application.MyApplication;
import com.app.utils.Const;
import com.app.utils.LoginUtil;
import com.app.utils.ObserverConst;
import com.app.utils.SdLocal;
import com.core.lib.utils.ObserverManager;
import com.core.lib.utils.main.AppManager;
import com.core.lib.utils.main.LogUtilBase;
import com.eyzhs.app.R;
import com.lepu.app.fun.chat.activity.OnlineActivity;
import com.lepu.app.fun.chat.adapter.ChattingAdapter;
import com.lepu.app.fun.chat.bean.ChatMessage;
import com.lepu.app.fun.chat.bean.ChatSession;
import com.lepu.app.fun.chat.bean.QuestionDeadLine;
import com.lepu.app.fun.chat.bean.UserInfo;
import com.lepu.app.fun.chat.business.chatcore.ChatDAO;
import com.lepu.app.fun.chat.business.chatcore.ChatManager;
import com.lepu.app.fun.chat.business.chatcore.MessageBuilder;
import com.lepu.app.fun.chat.business.chatcore.QuestionDao;
import com.lepu.app.fun.chat.business.uiflow.UITransition;
import com.lepu.app.fun.chat.util.CommonPopUpWindow;
import com.lepu.app.fun.chat.util.ReturnResult;
import com.lepu.app.fun.chat.util.StorageManager;
import com.lepu.app.widget.CustomTopBarNew;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import common.db.Constants;

/**
 * Created by changliu on 2015/01/27.
 */
public class BaseChattingFragment extends AbsBaseFragment implements MediaRecorder.OnErrorListener,
        CustomTopBarNew.OnTopbarNewLeftLayoutListener, CustomTopBarNew.OnTopbarNewRightButtonListener {
    private static final String TAG = BaseChattingFragment.class.getSimpleName();
    protected View view;
    protected ListView chatListView;
    protected LinearLayout uploadPhotoLineLayout;
    protected EditText chatInput;
    protected Button pressToTalkBtn;
    protected boolean isShowUploadPhoto = false, isPressToTalk = false;
    protected ImageView upLoadNativePhotoImgView, takePhotoImgView;
    protected ImageButton chatVoice;
    protected ChattingAdapter chattingAdapter;
    protected UserInfo userInfo;
    protected ImageButton sendButton;
    protected ChatSession chatSession;
    protected boolean sessionValid = false;
    protected Handler handler;
    protected ImageLoader imageLoader = ImageLoader.getInstance();
    protected List<ChatMessage> chatMessages;
    protected int duration;
    protected CountDownTimer countDownTimer;
    protected RelativeLayout recordingTipLayout;
    protected ImageView imgVoiceIcon;
    protected ImageView imgVoiceVolume;
    protected TextView txtCountDown;
    protected TextView txtVoiceTip;
    protected Boolean mFromHistory;
    protected boolean isPlaying = false;
    protected ImageView chatAdd;
    protected LinearLayout lineLayoutChat;//输入框

    protected static final int REQUESTCODE_TAKE = 1;        // 相机拍照标记
    protected String IMAGE_FILE_NAME = "askdrCaptureImage%s.jpg";
    protected String IMAGE_FOLDER = Environment.getExternalStorageDirectory() + "/DCIM/Camera";
    protected String newImageFilePath;

    protected final static int NA = -1;
    Bundle bundle = null;
    //// TODO: 2015/12/10  添加问题id 的判断
    private QuestionDeadLine questionDeadLine;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflateView(inflater, container);
        bundle = getArguments();
        if (!setupChatSession(bundle))
            return view;
        init();
        return view;
    }

    void init() {
        CustomTopBarNew topbar = (CustomTopBarNew) view.findViewById(R.id.topbar);
        topbar.setonTopbarNewLeftLayoutListener(this);
        topbar.setOnTopbarNewRightButtonListener(this);

        //判断是否来自历史记录
        try {
            Bundle bundle = getArguments();
            mFromHistory = bundle.getBoolean("from_history");
        } catch (Exception e) {
            e.printStackTrace();
        }

        imageLoader = ImageLoader.getInstance();
        imageLoader.init(ImageLoaderConfiguration.createDefault(getActivity()));
        handler = new Handler();
        uploadPhotoLineLayout = (LinearLayout) view.findViewById(R.id.lineLayout_upload_photo);
        chatInput = (EditText) view.findViewById(R.id.edt_chat_input);
        pressToTalkBtn = (Button) view.findViewById(R.id.btn_press_to_talk);
        chatListView = (ListView) view.findViewById(R.id.lstView_chat);
        chatVoice = (ImageButton) view.findViewById(R.id.imgBtn_chat_voice);
        chatAdd = (ImageView) view.findViewById(R.id.imgView_add);
        recordingTipLayout = (RelativeLayout) view.findViewById(R.id.relLayout_voice_tip);

        imgVoiceIcon = (ImageView) recordingTipLayout.findViewById(R.id.imgView_voice_icon);
        imgVoiceVolume = (ImageView) recordingTipLayout.findViewById(R.id.imgView_voice_volume);
        txtCountDown = (TextView) recordingTipLayout.findViewById(R.id.txt_countdown);
        txtVoiceTip = (TextView) recordingTipLayout.findViewById(R.id.txt_recording_tip);

        lineLayoutChat = (LinearLayout) view.findViewById(R.id.lineLayout_chat);

        sendButton = (ImageButton) view.findViewById(R.id.btn_send_message);
        sendButton.setOnClickListener(viewClickListener);
        chatVoice.setOnClickListener(viewClickListener);
        chatAdd.setOnClickListener(viewClickListener);
        // pressToTalkBtn.setOnTouchListener(touchListener);
        upLoadNativePhotoImgView = (ImageView) view.findViewById(R.id.imgView_upload_native_photo);
        takePhotoImgView = (ImageView) view.findViewById(R.id.imgView_take_photo);
        upLoadNativePhotoImgView.setOnClickListener(viewClickListener);
        takePhotoImgView.setOnClickListener(viewClickListener);
        topbar.setTopbarTitle(chatSession.getUserNickName());
        initExtra();
        chatInput.setOnTouchListener(inputTouchListener);
        chatInput.addTextChangedListener(textChangedListener);
        ;
        setMessageHandle();
        initChatMessages();


        chattingAdapter = setupChattingAdapter();
        setupChatListView();

        chatListView.setOnTouchListener(chatListViewOnTouchListener);
        StorageManager.getInstance().setupSessionFolder(chatSession.getSessionId());
    }

    protected View inflateView(LayoutInflater inflater, ViewGroup container) {
        return null;
    }

    protected void gotoOtherProfile(String userid) {
    }

    protected void gotoMineProfile() {
    }

    protected View.OnClickListener viewClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            processViewOnClick(view);
        }
    };

    TextWatcher textChangedListener = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
            sendButton.setVisibility(View.INVISIBLE);
            chatAdd.setVisibility(View.VISIBLE);
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
            if (charSequence.toString().equals("")) {
                sendButton.setVisibility(View.INVISIBLE);
                chatAdd.setVisibility(View.VISIBLE);
            } else {
                sendButton.setVisibility(View.VISIBLE);
                chatAdd.setVisibility(View.GONE);
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {
        }
    };

//    View.OnTouchListener touchListener = new View.OnTouchListener() {
//        @Override
//        public boolean onTouch(View view, MotionEvent motionEvent) {
//            return proceeViewOnTouch(view, motionEvent);
//        }
//    };

    View.OnTouchListener inputTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {

            if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                uploadPhotoLineLayout.setVisibility(View.GONE);
            }
            return false;
        }
    };

    View.OnTouchListener chatListViewOnTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                KeyBoardUtil.hideSoftKeyBoard(getActivity(), view);
            }
            return false;
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQUESTCODE_TAKE:// 调用相机拍照
                    try {
                        if (newImageFilePath == null || TextUtils.isEmpty(newImageFilePath))
                            return;
                        sendPhoto(newImageFilePath);
                    } catch (Exception e) {
                        LogUtilBase.LogD(TAG, e.toString());
                    }
                    break;
                default:
                    break;
            }
        }
    }

    public void goBack2ChatSessions() {
        if (chatSession != null) {
            chatSession.setNewMsgCount(0);
            // chat session message count 清零
            ChatManager.getInstance().resetNewMsgCount(chatSession.getSessionId());
        }
        Intent intent = new Intent(Constants.FILTER_ACTION_TO_CHAT_SESSIION);
        LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent);
        ObserverManager.getInstance().notify(ObserverConst.NOTIFY_ZXRECORDER_CHANGE, null, null);

        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                getActivity().finish();
                try {
                    if (AppManager.getAppManager().getActivity(OnlineActivity.class) != null)
                        AppManager.getAppManager().finishActivity(OnlineActivity.class);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                UITransition.setActivityFinishRightOut(getActivity());
            }
        }, 20);
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            goBack2ChatSessions();
            return true;
        }
        return false;
    }

    void sendMessage() {
        String sendTxt = chatInput.getText().toString();
        //todo throwbottleId  和瓶子id 进行区分
        if (!StringUtils.isEmpty(sendTxt.trim())) {
            if (sendTxt.length() > 1000) { //限制1000长度
                sendTxt = sendTxt.substring(0, 1000);
            }
            ChatMessage chatMessage = MessageBuilder.buildNewTextMessage(chatSession, sendTxt);
            chatMessage.setQuestionID(chatSession.getQuestionID());
            chatMessage.setQuestion(chatSession.getQuestion());
            ChatManager.getInstance().sendMessage(chatSession, chatMessage);

            chatInput.setText("");
            //KeyBoardUtil.hideSoftKeyBoard(getActivity(), view);
            //   chatListView.setSelection(chatMessages.size() - 1);
        } else {
            Toast.makeText(getActivity(), R.string.sendnull, Toast.LENGTH_SHORT).show();
            chatInput.setText("");
        }
    }

    void reSendMessage(int id) {
        ChatMessage message = chatMessages.get(id);
        chatMessages.remove(id);
        if (message.getMessageType() == Constants.Chat.CHAT_MESSAGE_TYPE_TEXT) {
            String sendStr = message.getContent();
            ChatMessage chatMessage = MessageBuilder.buildResendTextMessage(chatSession, sendStr, message.getMessageId());
            chatMessage.setQuestionID(chatSession.getQuestionID());
            chatMessage.setQuestion(chatSession.getQuestion());
            ChatManager.getInstance().sendMessage(chatSession, chatMessage);
            chatInput.setText("");
            // KeyBoardUtil.hideSoftKeyBoard(getActivity(), view);
//            chatListView.setSelection(chatMessages.size() - 1);
        }
    }

    void sendPhoto(String filePath) {
        File file = new File(filePath);

        if (file.exists()) {
            try {
                Bitmap bitmap = BimpUtils.resize2CommonImage(filePath);
                String endPath = SdLocal.getCacheImagePath(MyApplication.getInstance(), LoginUtil.getUserId(), String.valueOf(System.currentTimeMillis()));
                //ImageCompressUtils.saveBitmap(bitmap, endPath);
                saveBitmap(bitmap, endPath);
                Log.d(" base send Photo url:", endPath);
                ChatMessage chatMessage = MessageBuilder.buildNewImageMessage(chatSession, endPath, Constants.Chat.CHAT_IMAGE_STYLE_LARGE, (int) file.length(), false);
                chatMessage.setQuestionID(chatSession.getQuestionID());
                ChatManager.getInstance().prepareSendMediaMessage(chatSession, chatMessage);
            } catch (IOException e) {
                e.printStackTrace();
            }
            //TODO Chang , later need to decide LARGE or RAW by user

        }
    }

    void resendPhoto(String filePath, ChatMessage message) {
        File file = new File(filePath);
        if (file.exists()) {
            //TODO Chang , later need to decide LARGE or RAW by user
            ChatMessage chatMessage = MessageBuilder.buildResendImageMessage(message.getMessageId(), chatSession, filePath, Constants.Chat.CHAT_IMAGE_STYLE_LARGE, (int) file.length(), true);
            chatMessage.setQuestionID(chatSession.getQuestionID());
            ChatManager.getInstance().prepareSendMediaMessage(chatSession, chatMessage);
//            ChatManager.getInstance().startAsyncMediaOperation(MediaService.ACTION_UPLOAD_MEDIA, message.getMedia());
        }
    }

    public static void saveBitmap(Bitmap bitmap, String path) throws IOException {

        try {
            File file = new File(path);
            if (file.exists()) {
                return;
            }
            FileOutputStream out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
            LogUtilBase.LogD(TAG, "save bitmap error");
        }
    }

//    void sendAudio() {
//        if (newAudioFile == null || TextUtils.isEmpty(newAudioFile)) {
//            LogUtilBase.LogD(TAG, "no audio file found to send");
//            setupRecordingUI(View.GONE, NA, View.GONE, NA, View.GONE, null, View.VISIBLE, getString(R.string.recording_error_try_again), 0, View.VISIBLE);
//            handler.postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    //int iconView, int iconResId, int volumeView, int volumeResId, int countDownView,String countDownText, int voiceTipView, String tipText, int voiceTipBgResId, int layoutView
//                    setupRecordingUI(View.GONE, NA, View.GONE, NA, View.GONE, null, View.GONE, null, 0, View.GONE);
//                }
//            }, 1000);
//            return;
//        }
//
//        int vDuration = duration;
//        long size = 0;
//
//        try {
//            File file = new File(newAudioFile);
//            size = file.length();
//            MediaPlayer mp = MediaPlayer.create(getActivity(), Uri.parse(newAudioFile));
//            if (mp == null) { //xiaomi phone no try/catch the Exception
//                handler.removeCallbacks(voiceThread);
//                Toast.makeText(getActivity(), R.string.no_audio_permission, Toast.LENGTH_SHORT).show();
//                return;
//            } else {
//                vDuration = mp.getDuration();//即为时长 是ms
//                mp.release();
//            }
//        } catch (Exception e) {
//            LogUtilBase.LogE(TAG, e.toString());
//        }
//        LogUtilBase.LogD(TAG, "[recording] size=" + size + " duration=" + vDuration);
//        if (vDuration < 900) { //09.s
//            LogUtilBase.LogE(TAG, "can't send audio file with zero or 1s duration");
//            handler.removeCallbacks(voiceThread);
//            setupRecordingUI(View.VISIBLE, R.drawable.chat_vocie_icon_warning, View.GONE, NA, View.GONE, null, View.VISIBLE, getString(R.string.time_too_short), 0, View.VISIBLE);
//            handler.postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    //int iconView, int iconResId, int volumeView, int volumeResId, int countDownView,String countDownText, int voiceTipView, String tipText, int voiceTipBgResId, int layoutView
//                    setupRecordingUI(View.GONE, NA, View.GONE, NA, View.GONE, null, View.GONE, null, 0, View.GONE);
//                }
//            }, 2000);
//            return;
//        } else {
//            setupRecordingUI(View.GONE, NA, View.GONE, NA, View.GONE, null, View.GONE, null, 0, View.GONE);
//        }
//        vDuration = vDuration + 500;
//        ChatMessage chatMessage = MessageBuilder.buildNewAudioMessage(chatSession, newAudioFile, vDuration, (int) size, Constants.Chat.CHAT_MIME_TYPE_AMR, false);
//        if (mIsBottle) { //漂流瓶
//            chatMessage.setBottleID(mDBID);
//        } else {
//            chatMessage.setBottleID("sl");
//        }
//        ChatManager.getInstance().prepareSendMediaMessage(chatSession, chatMessage);
//    }

    public void reSendPhoto(final int position) {
        //todo
        final ChatMessage chatMessage = chatMessages.get(position);
        final CommonPopUpWindow tipPopWindow = new CommonPopUpWindow(getActivity(), R.layout.chat_dialog_common);
        tipPopWindow.registerDismissClick(R.id.layout_bg);
        tipPopWindow.registerDismissClick(R.id.btn_left);
        tipPopWindow.setTextContent(R.id.txt_title, getString(R.string.chat_is_resend_photo));
        tipPopWindow.registerClick(R.id.btn_right, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                chatMessages.remove(position);
                resendPhoto(chatMessage.getMedia().getFullName(), chatMessage);
                tipPopWindow.dismiss();
            }
        });
    }

//    @Override
//    public void onStop() {
//        super.onStop();
//        if (mp != null) {
//            mp.release();
//        }
//    }

//    void playAudio(int id, final ChattingAdapter.OnVoicePlayEnd onVoicePlayEnd) {
//        if (isPlaying) {
//            if (mp != null)
//                mp.release();
//        }
//        try {
//            ChatMessage chatMessage = chatMessages.get(id);
//            String audioFile = chatMessage.getMedia().getFullName();
//            mp = MediaPlayer.create(getActivity(), Uri.parse(audioFile));
//            final Timer timer = new Timer();
//            mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
//                @Override
//                public void onCompletion(MediaPlayer mp) {
//                    mp.release();
//                    timer.cancel();
//                    //播放完毕回调
//                    onVoicePlayEnd.OnPlayEnd();
//                    isPlaying = false;
//                    handler.postDelayed(new Runnable() {
//                        @Override
//                        public void run() {
//                            //int iconView, int iconResId, int volumeView, int volumeResId, int countDownView,String countDownText, int voiceTipView, String tipText, int voiceTipBgResId, int layoutView
//                            setupRecordingUI(View.GONE, NA, View.GONE, NA, View.GONE, null, View.GONE, null, 0, View.GONE);
//                        }
//                    }, 200);
//                }
//            });
//
//            final AudioManager audioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
//            mp.setLooping(false);
//            mp.start();
//            isPlaying = true;
//        } catch (Exception e) {
//            LogUtilBase.LogD(TAG, e.toString());
//        }
//    }

    public void showUploadPhoto(int position) {
        Bundle bundle = new Bundle();
        if (chatMessages.get(position).getDirection() == Constants.Chat.CHAT_DIRECTION_RECEIVE) {
            String objectId = chatMessages.get(position).getMedia().getObjectId();
            String largeImageId = chatMessages.get(position).getMedia().getLargeImageId();
            if (objectId.equals(largeImageId)) {
                bundle.putString(Constants.Chat.CHAT_IMAGE_OBJECT_ID, largeImageId);
            } else {
                bundle.putString(Constants.Chat.CHAT_IMAGE_OBJECT_ID, objectId);
            }
            bundle.putString(Constants.Chat.CHAT_IMAGE_OBJECT_ID, chatMessages.get(position).getMedia().getLargeImageId());
        } else {
            bundle.putString(Constants.Chat.CHAT_IMAGE_ATTACHFILE, chatMessages.get(position).getMedia().getFullName());
        }
        bundle.putString(Constants.Chat.CHAT_MESSAGE, "MEDIA_MESSAGE");
        bundle.putString(Constants.Chat.CHAT_SESSION, String.valueOf(chatSession.getSessionId()));
        performGoAction("gotoPhotoDisplay", bundle);
    }


    void showUploadPhotoView() {
        if (isShowUploadPhoto) {
            uploadPhotoLineLayout.setVisibility(View.GONE);
        } else {
            uploadPhotoLineLayout.setVisibility(View.VISIBLE);
        }
        isShowUploadPhoto = !isShowUploadPhoto;
        KeyBoardUtil.hideSoftKeyBoard(getActivity(), chatInput);
        chatListView.setSelection(chatMessages.size() - 1);
    }

    /**
     * 录音
     */
//    void showPressToTalk() {
//        uploadPhotoLineLayout.setVisibility(View.GONE);
//        sendButton.setVisibility(View.INVISIBLE);
//        if (!isPressToTalk) {
//            chatVoice.setImageResource(R.drawable.chat_keyborder_nor);
//            pressToTalkBtn.setVisibility(View.VISIBLE);
//            chatInput.setVisibility(View.INVISIBLE);
//            if (imgViewStar != null) {
//                imgViewStar.setVisibility(View.GONE);
//            }
//        } else {
//            chatVoice.setImageResource(R.drawable.chat_icon_voice_selector);
//            pressToTalkBtn.setVisibility(View.GONE);
//            chatInput.setVisibility(View.VISIBLE);
//            if (imgViewStar != null) {
//                imgViewStar.setVisibility(View.VISIBLE);
//            }
//
//            sendButton.setVisibility(TextUtils.isEmpty(chatInput.getText()) ? View.INVISIBLE : View.VISIBLE);
//        }
//        isPressToTalk = !isPressToTalk;
//        KeyBoardUtil.hideSoftKeyBoard(getActivity(), chatInput);
//    }
    protected void addImageNote(View view, int id) {
    }

//    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
//    private void startRecording() {
//        try {
//            String newFile = "audio-" + System.currentTimeMillis() + ".amr";
////            String newFile = StorageManager.getInstance().getNewAudioFileName("amr");
//            newAudioFile = StorageManager.getInstance().createFile(newFile, chatSession.getSessionId());
//            if (newAudioFile == null || newAudioFile.isEmpty()) {
//                LogUtilBase.LogE(TAG, "can't create new file " + newAudioFile);
//                return;
//            }
//
//            recorder = new MediaRecorder();// new出MediaRecorder对象
//            if (recorder == null) {
//                return;
//            }
//            recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
//            recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
//            recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
//            recorder.setOutputFile(newAudioFile);
//            recorder.setMaxDuration(60000);
//            duration = 0;
//            recordStart = System.currentTimeMillis();
//            recorder.prepare();// 准备录制
//            recorder.start();// 开始录制
//        } catch (Exception e) {
//            Toast.makeText(getActivity(), R.string.no_audio_permission, Toast.LENGTH_SHORT).show();
//            LogUtilBase.LogD(TAG, e.toString());
//            return;
//        }
//        countDownTimer.start();
////            MediaPlayer mp = MediaPlayer.create(getActivity(), Uri.parse(newAudioFile));
////            if (mp == null) {
////                final CommonPopUpWindow noPermissionPop = new CommonPopUpWindow(getActivity(), R.layout.dialog_common_tip);
////                View contentView = noPermissionPop.getPoPView();
////                TextView txtContent = (TextView) contentView.findViewById(R.id.txt_content);
////                txtContent.setText(getString(R.string.recording_tip));
////                noPermissionPop.registerDismissClick(R.id.layout_bg);
////                noPermissionPop.registerClick(R.id.btn_yes, new View.OnClickListener() {
////                    @Override
////                    public void onClick(View view) {
////                        startActivity(new Intent(Settings.ACTION_SETTINGS));
////                        noPermissionPop.dismiss();
////                    }
////                });
////
////                hasRecordingPermission = false;
////                return;
////            } else {
////                Toast.makeText(getActivity(), "test", Toast.LENGTH_SHORT).show();
////                hasRecordingPermission = true;
////                mp.release();
////            }
//
//        isInCountDown = false;
//
//        voiceThread = new VoiceThread();
//        handler.postDelayed(voiceThread, 1000);
//    }
//
//    private void stopRecording() {
//        LogUtilBase.LogE(TAG, "[recording] stopRecording");
//
//        try {
//            countDownTimer.cancel();
//            duration = (int) (System.currentTimeMillis() - recordStart);
//
//            if (recorder == null) {
//                LogUtilBase.LogD(TAG, "[recording] stopRecording recorder=null");
//                return;
//            }
//            recorder.stop();
//            recorder.release();
//            recorder = null;
//            handler.postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    try {
//                        LogUtilBase.LogD(TAG, "[recording] postDelayed to turnoff UI");
//                        //int iconView, int iconResId, int volumeView, int volumeResId, int countDownView,String countDownText, int voiceTipView, String tipText, int voiceTipBgResId, int layoutView
//                        setupRecordingUI(View.GONE, NA, View.GONE, NA, View.GONE, null, View.GONE, null, NA, View.GONE);
//                    } catch (Exception e) {
//                        LogUtilBase.LogD(TAG, e.toString());
//                    }
//                }
//            }, 1000);
//        } catch (Exception e) {
//            LogUtilBase.LogD(TAG, "[recording] stopRecording error=" + e.getMessage());
//            LogUtilBase.LogD(TAG, e.toString());
//        }
//    }

    protected void setAdd2NotePopMenu(View view, final int id) {
    }

    private void setMessageHandle() {
        Handler h = new Handler() {
            public void handleMessage(Message msg) {
                Bundle data = msg.getData();
                ChatMessage message = (ChatMessage) data.getSerializable(Constants.Chat.CHAT_MESSAGE);
                if (null == message) {
                    return;
                }
                long sessionId = chatSession.getSessionId();
                //漂流瓶不进行判断

                //// TODO: 2015/12/21  注释 
                if (sessionId != message.getSessionId()) {
                    return;
                }
                boolean isNew = false;
                switch (msg.what) {
                    case Constants.Chat.CHAT_MESSAGE_SENT:
                        LogUtilBase.LogD(TAG, "Chatting Room:CHAT_MESSAGE_SENT");

                        if (chatSession != null) {
                            //标题没有发出来，进行重发
                            if (chatSession.getQuestion().equals(message.getContent())) {
                                chatMessages.add(0, message);
                            } else {
                                chatMessages.add(message);
                            }
                        }
                        //chatMessages.add(message);
                        chattingAdapter.notifyDataSetChanged();
                        chatListView.setSelection(chatListView.getCount() - 1);
                        break;
                    case Constants.Chat.CHAT_MESSAGE_RECEIVED:
                        LogUtilBase.LogD(TAG, "Chatting Room:CHAT_MESSAGE_RECEIVED");
                        isNew = true;
                        for (int i = 0; i < chatMessages.size(); i++) {
                            if (chatMessages.get(i).getMessageId().equals(message.getMessageId())) {
                                chatMessages.set(i, message);
                                chatMessages.remove(i);
                                isNew = false;
                                break;
                            }
                        }
                        if (isNew) {
                            chatMessages.add(message);
                        }
                        chattingAdapter.notifyDataSetChanged();
                        chatListView.setSelection(chatListView.getCount() - 1);
                        break;
                    case Constants.Chat.CHAT_MESSAGE_CHANGED:
                        changeMessage(message);
                        break;
                    case Constants.Chat.CHAT_MESSAGE_REPLACE:
                        LogUtilBase.LogD(TAG, "Chatting Room:CHAT_MESSAGE_REPLACE");
                        message = (ChatMessage) data.getSerializable("message");
                        for (int i = 0; i < chatMessages.size(); i++) {
                            if (chatMessages.get(i).getMessageId().equals(message.getMessageId())) {
                                chatMessages.remove(i);
                                break;
                            }
                        }
                        chatMessages.add(message);
                        chattingAdapter.notifyDataSetChanged();
                        chatListView.setSelection(chatListView.getCount() - 1);
                        break;

                    case Constants.Chat.CHAT_MESSAGE_DOWNLOAD_MEDIA:
                        //NO need to implement
                        //Media media = (Media) data.getSerializable("media");
                        //MediaManager.getInstance().loadImage(chatSession,media, Constants.Http.HTTP_DOWNLOAD_IMAGE_THUMBNAIL,new ImageLoader(), new ImageView());
                        break;
                }
            }
        };

        MyApplication.getInstance().setChatMsgHandler(h);
    }

    /**
     * 接受到消息进行处理
     *
     * @param message
     */
    private void changeMessage(ChatMessage message) {
        LogUtilBase.LogD(TAG, "Chatting Room:CHAT_MESSAGE_CHANGED");
        for (int i = 0; i < chatMessages.size(); i++) {
            if (chatMessages.get(i).getMessageId().equals(message.getMessageId())) {
                chatMessages.set(i, message);
                break;
            }
        }
        //自己发出去的 刷新单个
        if (message.getDirection() == 1) {
            ProgressBar progressBar = (ProgressBar) chatListView.findViewWithTag(message.getMessageId());
            if (progressBar != null) {
                progressBar.setVisibility(View.GONE);
            }
            if (message.getSendStatus() == 4) { //显示重发
                //// TODO: 2015/12/16  注释
//                if (!CheckNetUtil.checkNetWork(getActivity())) {
//                    chattingAdapter.notifyDataSetChanged();
//                } else {
//                    ImageView reImageView = (ImageView) chatListView.findViewWithTag("re" + message.getMessageId());
//                    if (reImageView != null) {
//                        reImageView.setVisibility(View.VISIBLE);
//                    }
//                }
            }
        } else if (message.getDirection() == 2) { //接收到的
            chattingAdapter.notifyDataSetChanged();
        }
        if (chatListView.getCount() > 6)
            chatListView.setSelection(chatListView.getCount() - 1);
    }

    @Override
    public void onError(MediaRecorder mr, int what, int extra) {
        LogUtilBase.LogE(TAG, what + extra + "");
    }

    private void processViewOnClick(View view) {
        switch (view.getId()) {
            case R.id.imgBtn_chat_voice:
                // showPressToTalk();
                break;
            case R.id.imgView_add:
                showUploadPhotoView();
                break;
            case R.id.imgView_take_photo:
                Intent takeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                String imageName = String.format(IMAGE_FILE_NAME, DateUtil.getNowDate("yyyyMMddHHMMss"));
                File file = new File(IMAGE_FOLDER, imageName);
                newImageFilePath = file.getPath();
                takeIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                startActivityForResult(takeIntent, REQUESTCODE_TAKE);
                break;
            case R.id.btn_send_message:
                sendMessage();
                break;
            case R.id.imgView_upload_native_photo:
                Bundle bundle = new Bundle();
                bundle.putInt(Constants.PHOTO_SELECTED_MAX_ALLOW_SELECT_NUMBER, 9);
                performGoAction("gotoAlbum", bundle, new ReturnResult() {
                    @Override
                    public void onResult(int resultCode, Bundle resultData) {
                        //todo
                        uploadPhotoLineLayout.setVisibility(View.GONE);
                        ArrayList<ImageItem> thisSelectedImages = (ArrayList) resultData.getSerializable(Constants.PHOTO_SELECTED_SELECTED_IMAGES);
                        for (int i = 0; i < thisSelectedImages.size(); i++) {
                            sendPhoto(thisSelectedImages.get(i).imagePath);
                        }
                    }
                });
                break;
            default:
                break;
        }
    }

    protected void initExtra() {
    }


    private boolean setupChatSession(Bundle bundle) {
        chatSession = (ChatSession) bundle.getSerializable(Constants.Chat.CHAT_SESSION);
        try {
            questionDeadLine = (QuestionDeadLine) bundle.getSerializable(Const.QUESTIONDEADLINE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        userInfo = (UserInfo) bundle.getSerializable(Constants.USER_INFO);
        //todo 没有使用这里的判断
        if (chatSession == null) {
            if (userInfo == null) {
                LogUtilBase.LogD(TAG, "onCreateView UserInfo is null!");
                return false;
            }
            chatSession = ChatManager.getInstance().getOrCreateChatSession(Long.valueOf(LoginUtil.getUserId()), userInfo);
            if (chatSession == null) {
                LogUtilBase.LogD(TAG, "onCreateView chatsession is null!");
                return false;
            }
        } else {
            if (chatSession.getLastMsgContent().equals(Constants.Counts.NEW_PATIENT_FLAG)) {
                chatSession.setLastMsgContent(MyApplication.getInstance().getString(R.string.chat_message_new_relation_patient));
                //todo  插入session的时候  id
                ChatDAO.getInstance().updateChatSession(chatSession);
            }
        }
        return true;
    }

    private ChattingAdapter setupChattingAdapter() {
        ChattingAdapter chattingAdapter = new ChattingAdapter(getActivity(), chatMessages, imageLoader, new FragmentCallback() {
            @Override
            public void requestResendPhoto(int id) {
                reSendPhoto(id);
            }

            @Override
            public void showLargePhoto(int id) {
                showUploadPhoto(id);
            }

            @Override
            public void addTextToNote(View view, int id) {
                // setAdd2NotePopMenu(view, id);
            }

            @Override
            public void reSendContent(int id) {
                reSendMessage(id);
            }

            @Override
            public void intentPatientInfo() {

            }

            @Override
            public void addImageToNote(View view, int id) {
//                addImageNote(view, id);
            }

            @Override
            public void playVoice(int id, ChattingAdapter.OnVoicePlayEnd onVoicePlayEnd) {
                // playAudio(id, onVoicePlayEnd);
            }

            @Override
            public void stopVoid(int id) {
                // stopVoice(id);
            }

            @Override
            public void gotoProfile(String direction, String userid) {
                LogUtilBase.LogD(TAG, "gotoProfile - " + direction);
                if (direction.equals(Constants.DOCTOR))
                    gotoOtherProfile(userid);
                else if (direction.equals(Constants.PATIENT))
                    gotoMineProfile();
                else
                    LogUtilBase.LogD(TAG, "gotoProfile invalid direction=" + direction);
            }

            @Override
            public void hiddenChatBox(boolean isHidden) {
                if(isHidden){
                    if(lineLayoutChat!=null)
                    lineLayoutChat.setVisibility(View.GONE);
                }else {
                    if(lineLayoutChat!=null)
                    lineLayoutChat.setVisibility(View.VISIBLE);
                }
            }

        });
        return chattingAdapter;
    }


    private void initChatMessages() {
//        chatMessages = ChatManager.getInstance().getChatMessages(Long.valueOf(chatSession.getQuestionID()));
        chatMessages = ChatManager.getInstance().getChatMessages(chatSession.getSessionId());
        if (null == chatMessages) {
            chatMessages = new ArrayList<ChatMessage>();
        } else {
            for (int i = 0; i < chatMessages.size(); i++) {
                chatMessages.get(i).setGuestProfilePicId(chatSession.getUserProfilePictureId());
            }
            //修改流程 按照次数进行收费
            //// TODO: 2015/12/10 暂时不进行调整
            if (userInfo != null && !TextUtils.isEmpty(userInfo.getQuestion())) {
                //发送内容 从 在线咨询过来的
                ChatMessage chatMessage = MessageBuilder.buildNewTextMessage(chatSession, userInfo.getQuestion());
                chatMessage.setQuestionID(chatSession.getQuestionID());
                chatMessage.setQuestion(chatSession.getQuestion());
                chatMessage.setRecordCreateTime(chatSession.getRecordCreateTime());
                ChatManager.getInstance().sendMessage(chatSession, chatMessage);
            } else if (chatMessages.size() == 0) {
//                ChatMessage chatMessage = MessageBuilder.buildNewTextMessage(chatSession, userInfo.getQuestion());
                ChatMessage chatMessage = MessageBuilder.buildNewTextMessage(chatSession, chatSession.getQuestion());
                chatMessage.setQuestionID(chatSession.getQuestionID());
                chatMessage.setRecordCreateTime(questionDeadLine.RemainTime);
                chatMessage.setIsClosed(questionDeadLine.IsClosed);
                if (!mFromHistory) { //新的需要发送
                    ChatManager.getInstance().sendMessage(chatSession, chatMessage);
                } else {//历史记录不发送。直接添加
                    chatMessage.setSendStatus(2);
                    chatMessages.add(chatMessage);
                }
            } else if (chatMessages.get(0) != null) {
                //设置过期时间
                chatMessages.get(0).setRecordCreateTime(questionDeadLine.RemainTime);
                chatMessages.get(0).setIsClosed(questionDeadLine.IsClosed);
            }
//                //1 如果是漂流瓶 touserid 扔瓶子人的id, 瓶子id
//                ChatManager.getInstance().sendMessage(chatSession, chatMessage);
////                String str = getResources().getString(R.string.chat_tip);
//                ChatMessage chatMessage = MessageBuilder.buildNewTextMessage(chatSession, userInfo.getRequestQuestion());
//                chatMessage.setDirection(1);//发出去
//                //// TODO: 2015/12/10
////                if (questionDeadLine == null)
////                    questionDeadLine = new QuestionDeadLine();
////                chatMessage.setIsClosed(questionDeadLine.IsClosed);
////                chatMessage.setRecordCreateTime(questionDeadLine.RecordCreateTime);
//
//                chatMessage.setSendStatus(Constants.Chat.CHAT_SEND_STATUS_RECEIVED);
//                chatMessages.add(0, chatMessage);
            //}
        }
    }

    private void setupChatListView() {
        chatListView.setAdapter(chattingAdapter);
        if (chatMessages.size() >= 1) {
            chatListView.setSelection(chatMessages.size() - 1);
        }
    }

    @Override
    public void onTopbarLeftLayoutSelected() {
        KeyBoardUtil.hide(getActivity());
        goBack2ChatSessions();
    }

    @Override
    public void onTopbarRightButtonSelected() {
        //// TODO: 2015/11/30  点击右边
//        Intent intent = new Intent(getActivity(), PersonMeterialActivity.class);
//        intent.putExtra(Const.TOJID, String.valueOf(chatSession.getUserId()));
//        getActivity().startActivity(intent);
//        UITransition.setActivityStartRightIn(getActivity());
    }


}